package FeedMaker;

import java.io.File;
import java.io.FileOutputStream;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;

public class XmlWriter 
{
	public Document doc_;
	
	public XmlWriter()
	{		
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		
		try 
		{
			doc_ = dbf.newDocumentBuilder().newDocument();
		} 
		catch (ParserConfigurationException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void save( String filename )
	{		
		if( doc_ != null && filename != null )
		{
			try
			{
				DOMSource source = new DOMSource(doc_);
				
				File path = new File( filename.substring( 0, filename.lastIndexOf("/") ) );
				
				if( !path.isDirectory() )
				{
					path.mkdirs();
				}
				
				FileOutputStream fo = new FileOutputStream( new File(filename) );
				
				StreamResult result = new StreamResult( fo );
				
				TransformerFactory tf = TransformerFactory.newInstance();
				
				Transformer t = tf.newTransformer();
				
				t.setOutputProperty( OutputKeys.ENCODING, "utf-8" );
				t.setOutputProperty( OutputKeys.INDENT, "yes" );
				
				t.transform(source, result);
				
				fo.close();
			} 
			catch (Exception e) 
			{
				// TODO Auto-generated catch block
				//e.printStackTrace();
			}
		}
	}
}
